<template>
    <div class="search">
        <div class="box">
            <div class="input">
                <input type="text" v-model="text" @keydown="chose" @focus="show = true" @blur="show = false" :class="show ? 'focus' : ''">
                <ul class="history" v-show="show">
                    <li :class="cur === i ? 'active' : ''" v-for="(item, i) in history" :key="i">{{item}}</li>
                </ul>
            </div>
            <button @click="search">百度一下</button>
        </div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            show: false,
            text: '',
            history: [],
            cur: 0
        }
    },
    created() {
        if(localStorage.getItem('history')) {
            this.history = JSON.parse(localStorage.getItem('history'))
        }
    },

    methods: {
        search() {
            if(!this.text) return
            this.history.unshift(this.text)
            this.history = [...new Set(this.history)]
            localStorage.setItem('history', JSON.stringify(this.history))
        },


        chose(e) {
            // console.log(e);
            // debugger
            if(e.keyCode === 38) { // 表示 点击的事键盘的up键
                if(this.cur === 0) {
                    this.cur = this.history.length - 1
                } else {
                    this.cur--
                }
                this.text = this.history[this.cur]
            } else if(e.keyCode === 40) {
                if(this.cur === this.history.length - 1) {
                    this.cur = 0
                } else {
                    this.cur++
                }
                this.text = this.history[this.cur]
            }
        }
    }
}
</script>
<style lang="scss">
    * {box-sizing: border-box;}
    ul {
        list-style: none;
        padding: 0;
        margin: 0;
        li {
            line-height: 40px;
        }
        .active {
            color: blue;
        }
    }
    .box {
        width: 1000px;
        margin: 0 auto;
        display: flex;
        margin-top: 100px;
        .input {
            width: 600px;
            border: 2px solid #c4c7ce;
            min-height: 50px;
            border-top-left-radius: 6px;
            border-bottom-left-radius: 6px;
            padding:0 10px;
            input {
                width: 100%;
                height: 46px;
                border: none;
                outline: none;
            }
            .focus {
                border-bottom: 1px solid #eee;
            }
        }
        button {
            width: 120px;
            background:#4e6ef2;
            color: #fff;
            outline: none;
            border: none;
            height: 50px;
            border-top-right-radius: 6px;
            border-bottom-right-radius: 6px;
            font-size: 18px;
            margin-left: -2px;
        }
    }
</style>


